#!/cygdrive/c/Python27/python

import feedparser
import urllib2
import codecs
import sqlite3
import datetime
import sys

from wx import Frame, DefaultPosition, Size, Menu, MenuBar, App, grid
from wx import EVT_MENU, EVT_CLOSE

from twisted.python import log
from twisted.internet import wxreactor
wxreactor.install()

# import t.i.reactor only after installing wxreactor:
from twisted.internet import reactor

# should just check file type is audio/video whatevs
def addToFileList(stringToTest):
    try:
        for fileType in fileTypeList:
            if(stringToTest.find(fileType) > -1):
                fileList.append(stringToTest)
    except:
        print('Couldn\'t add')

# this is just a traversal function, not used but retained as is useful for trouble shooting
def itObj(parent):
    try:
        '' + parent
        addToFileList(parent)
    except TypeError:
        try:
            # if the parent is an array the child will be the actual parent[child]
            for child in parent:
                try:
                    '' + child # will this cause unwanted type errors?
                    itObj(parent[child])
                except TypeError:
                    try:
                        itObj(child)
                    except TypeError:
                        try:
                            '' + parent[child]
                        except TypeError:
                            '' + child
        except:
            print('error' + parent)
            return

# just a hack for now, needs to check with operating system?
# maybe just don't download text/html or get the user to OK certain types
def isMedia(type):
    if(type == 'audio/mpeg'):
        return True

# this needs to be non-blocking
def download(url):
    file_name = url.split('/')[-1]
    u = urllib2.urlopen(url)
    # todo: check folder exists
    # todo: check if we've already downloaded it
    # todo: podcasts go into own directory which is user selectable
    f = open('podcasts/' + file_name, 'wb')
    meta = u.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    print "Downloading: %s Bytes: %s" % (file_name, file_size)
    
    file_size_dl = 0
    block_sz = 8192
    while True:
        buffer = u.read(block_sz)
        if not buffer:
            break
    
        file_size_dl += len(buffer)
        f.write(buffer)
        status = r"%10d mb [%3.2f%%]" % (file_size_dl/ 1024/1024 , file_size_dl * 100. / file_size)
        status = status + chr(8)*(len(status)+1)
        print(status,)
    
    f.close()

def dictFactory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

ID_EXIT  = 101
ID_DOWNLOAD = 102

def createDatabase():
    c = conn.cursor()
    c.execute("CREATE TABLE IF NOT EXISTS feed(feedId INTEGER PRIMARY KEY, name text, url text, lastChecked timestamp)")
    c.execute("CREATE TABLE IF NOT EXISTS entry(entryId INTEGER PRIMARY KEY, title text, summary text, createDate timestamp)")
    c.execute("CREATE TABLE IF NOT EXISTS mediaType(mediaTypeId INTEGER PRIMARY KEY, type text, download bool)") # audio/mpeg etc
    
#>>> import wx
#>>> import wx.grid
#>>> class MyApp(wx.App):
#...     def OnInit(self):
#...         frame = wx.Frame(None, -1, title = "wx.Grid - Bitmap example")
#...         grid = wx.grid.Grid(frame)
#...         grid.CreateGrid(1,1)
#...         img = wx.Bitmap("python-logo.png", wx.BITMAP_TYPE_PNG)
#...         imageRenderer = MyImageRenderer(img)
#...         grid.SetCellRenderer(0,0,imageRenderer)
#...         grid.SetColSize(0,img.GetWidth()+2)
#...         grid.SetRowSize(0,img.GetHeight()+2)
#...         frame.Show(True)
#...         return True
#
#>>> class MyImageRenderer(wx.grid.PyGridCellRenderer):
#...     def __init__(self, img):
#...         wx.grid.PyGridCellRenderer.__init__(self)
#...         self.img = img
#...     def Draw(self, grid, attr, dc, rect, row, col, isSelected):
#...         image = wx.MemoryDC()
#...         image.SelectObject(self.img)
#...         dc.SetBackgroundMode(wx.SOLID)
#...         if isSelected:
#...             dc.SetBrush(wx.Brush(wx.BLUE, wx.SOLID))
#...             dc.SetPen(wx.Pen(wx.BLUE, 1, wx.SOLID))
#...         else:
#...             dc.SetBrush(wx.Brush(wx.WHITE, wx.SOLID))
#...             dc.SetPen(wx.Pen(wx.WHITE, 1, wx.SOLID))
#...         dc.DrawRectangleRect(rect)
#...         width, height = self.img.GetWidth(), self.img.GetHeight()
#...         if width > rect.width-2:
#...             width = rect.width-2
#...         if height > rect.height-2:
#...             height = rect.height-2
#...         dc.Blit(rect.x+1, rect.y+1, width, height, image, 0, 0, wx.COPY, True)
#
#>>> app = MyApp(0)
#>>> app.MainLoop()


class mainFrame(Frame):
    def __init__(self, parent, ID, title):
        Frame.__init__(self, parent, ID, title, DefaultPosition, Size(300, 200))
        menu = Menu()
        menu.Append(ID_EXIT, "E&xit", "Terminate the program")
        menu.Append(ID_DOWNLOAD, "&Download", "Download stuff")
        menuBar = MenuBar()
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)
        EVT_MENU(self, ID_EXIT,  self.DoExit)
        EVT_MENU(self, ID_DOWNLOAD,  self.DoDownload)
        
        g = grid.Grid(self)
        g.CreateGrid(1,1)
        
        # make sure reactor.stop() is used to stop event loop:
        EVT_CLOSE(self, lambda evt: reactor.stop())

    def DoExit(self, event):
        reactor.stop()
    def DoDownload(self, event):
        pass
        #download("www.google.com.au")

class feedGrabber(App):
    def twoSecondsPassed(self):
        print("two seconds passed")

    def OnInit(self):
        frame = mainFrame(None, -1, "Hello, world")
        frame.Show(True)
        self.SetTopWindow(frame)
        # look, we can use twisted calls!
        reactor.callLater(2, self.twoSecondsPassed)
        # return True

        conn = sqlite3.connect('feed.sqlite')
        conn.row_factory = dictFactory
        c = conn.cursor()
        
        """
        for each feed we want to track:
            how often deleted without listening
            how often listened through to end
            "       " skipped stuff
            "       " paused
            number of episodes listened to
            whether they tried the feed and unsubscribed
            how soon after downloading (if not automatically downloaded) the episode was listened to
        """
        # insert a new feed
        # feed = feedparser.parse('http://www.google.com/reader/public/atom/user%2F01961322947913245777%2Fbundle%2FListen%20Subscriptions')
        # c.execute("insert into feed (name, url, lastChecked) values (?,?,?)", (feed.feed.title, feed.feed.links[0].href, datetime.datetime.now()))

        # this stuff needs to be done in like reactor.callLater or something
        c.execute('select * from feed')
        
        print("got feeds")
        for row in c:
            feed = feedparser.parse(row['url'])
            #print (feed.feed)
            print (feed.feed.title)
            for entry in feed.entries:
                print('\n' + entry.title + ' ' + entry.updated)
                for link in entry.links:
                    if(isMedia(link.type)):
                        reactor.callLater(1, download, link.href)
                        # download(link.href)
                break
            
        conn.close()
        
        return True

if __name__ == "__main__":
    log.startLogging(sys.stdout)
    print("App start")
    app = feedGrabber(0)
    reactor.registerWxApp(app)
    reactor.run()
